package io.sunny.platform.ai.deepseek.client;

import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import io.github.pigmesh.ai.deepseek.core.chat.AssistantMessage;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionChoice;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.sunny.platform.ai.deepseek.config.DeepSeekConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

/**
 * @Author SUNNY
 * @Date 2025/11/29 9:41
 * @PackageName: io.sunny.platform.ai.deepseek.client
 * @Description: 高可用客户端（支持熔断、重试）
 * @Version 1.0
 */
@Slf4j
@Component
public class HighAvailableDeepSeekClient {
    private final DeepSeekClient deepSeekClient;
    private final CircuitBreaker circuitBreaker;
    private final Retry retry;

    public HighAvailableDeepSeekClient(DeepSeekConfigProperties config) {
        this.deepSeekClient = new DeepSeekClient.Builder()
                .openAiApiKey(config.getKey())
                .baseUrl(config.getBaseUrl())
                .connectTimeout(config.getTimeout().getConnect())
                .readTimeout(config.getTimeout().getRead())
                .build();

        // 熔断配置器：5分钟内失败率超过50%时开启熔断
        this.circuitBreaker = CircuitBreaker.of("deepSeekBreaker",
                CircuitBreakerConfig.custom()
                        .failureRateThreshold(50)
                        .waitDurationInOpenState(Duration.ofMinutes(1))
                        .slidingWindowSize(10)
                        .build());

        // 重试配置：指数退避策略
        this.retry = Retry.of("deepSeekRetry",
                RetryConfig.custom()
                        .maxAttempts(config.getRetry().getMaxAttempts())
                        .waitDuration(config.getRetry().getBackoffDelay())
                        .build());
    }

    @io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker(name = "deepSeekBreaker",
            fallbackMethod = "fallbackResponse")
    @io.github.resilience4j.retry.annotation.Retry(name = "deepSeekRetry")
    public ChatCompletionResponse generateWithHighAvailability(ChatCompletionRequest request) {
        try {
            return deepSeekClient.chatCompletion(request).execute();
        } catch (Exception e) {
            log.error("DeepSeek API调用失败：{}", e.getMessage(), e);
            throw new RuntimeException("AI服务暂时不可用");
        }
    }

    /**
     * 降级方法
     */
    private ChatCompletionResponse fallbackResponse(ChatCompletionRequest request, Exception e) {
        log.warn("触发降级策略，请求内容：{}", request.messages());
        return ChatCompletionResponse.builder()
                .id("fallback")
                .choices(List.of(ChatCompletionChoice.builder()
                        .message(AssistantMessage.from("AI服务繁忙，请稍后重试")).build()))
                .build();
    }
}
